//
//  ShoppingOrderDetailCtr.swift
//  smosky
//
//  Created by zhuxietong on 2018/7/6.
//  Copyright © 2018年 tianrun. All rights reserved.
//

import Foundation
import soapp
import AsyncDisplayKit
import Foundation
import Eelay

//enum NavPresentType {
//    case defaultPush
//    case backSkip(Int)
//    case navRootPresent
//}

open class ShoppingOrderDetailCtr: ASListController {
    var scheme = SaleScheme.normal

    open var sections:TP.section{
        get{
            
            var section1 = [[String:Any]]()
            if mo.detail["order.address.id",""].len > 0
            {
                let address = DataNode.path(node: "order.address", mo.detail, value: NSMutableDictionary())
                section1.append(["cellID":"address","__model":address])
            }
            let order = mo.detail
            order["__scheme"] = scheme.rawValue
            
            let sec:TP.section = [
                [
                    ["cellID":"status","__model":order],
                ],
                section1,
                [
                    ["cellID":"goods","__model":order],
                    ["cellID":"price","__model":order],
                    ["cellID":"sn","__model":order],
                    ["cellID":"actions","__model":order],
                    ["cellID":"log_header","icon":"wddd_rz","title":"\(OrderScheme.default.name)\("日志".loc)"],
                    ["cellID":"logs","__model":order]
                ]
            ]
            return sec
        }
    }
    
    public let selector:TP.selector = [
        "cellID<status>":StatusCell.self,
        "cellID<goods>":GoodsCell.self,
        "cellID<address>":AddressCell.self,
        "cellID<price>":PriceCell.self,
        "cellID<sn>":OrderSnCell.self,
        "cellID<logs>":LogCell.self,
        "cellID<log_header>":LogHeader.self,
        "cellID<actions>":Goods.BtsStatusCell.self
    ]
    
    open var orderID:String{
        get{
            var id = mo.model["order.id",""]
            if id.len < 1
            {
                id = mo.model["id",""]
            }
            if id.len < 1
            {
                id = mo.model["orderid",""]
            }
            return id
        }
    }
    
    override open func mo_request_send() {
        GMsgType.goods_order.msg.readOne(ID: orderID)
        weak var wself = self
        loadingV.loading()
        JoTask().get.log.params(["orderid":orderID]).log_response()._surl(.订单详情).json_handle { (status, msg, obj, resp) in
            wself?.loadingV.dismiss()
            if status.isSuccess{
                if let dict = obj as? NSMutableDictionary{
                    wself?.mo.detail = dict
                    return
                }
            }
            wself?.mo_request_alert(msg: msg, title: "", bt_title: "重试".loc)
        }.run()
    }
    
    override open func mo_detail_reload() {
        tableNode.load(sections: sections, selector: selector)
        tableNode.reloadData()
        //        let msgid = MsgMap.getMsgID(type: .order, objID: self.orderID)
        GMsgType.goods_order.msg.readOne(ID: orderID)
        
    }
    
    override open func mo_model_reload() {
        switch self.scheme {
        case .normal:
             self.__link = EeURLCreator(path: MallRouter.商品订单.rawValue, params: ["id":orderID]).rawUrl
        case .group:
            break
        }
     
    }
    
    
    override open func viewDidLoad() {
        super.viewDidLoad()
        self.title = "订单详情".loc

        
        mo_request_send()
        weak var wself = self
        __notice.observer(Goods.Notice.goodsOrderChange,Goods.Notice.groupOrderChange) { (noticeType, notify) in
            wself?.mo_request_send()
        }
        tableView.backgroundColor = ._tableBackground
    }
    
    
    
    override open func touch(cell: Any, actionID: String, model: NSMutableDictionary) {
        switch actionID {
        case "deleteItem":
            __post(notify: Goods.Notice.goodsOrderChange, object: model, userInfo: ["action":actionID])
            dismissAction()
        case "canleItem":
            __post(notify: Goods.Notice.goodsOrderChange, object: model, userInfo: ["action":actionID])
            //            canle()
            
        case "applySaleAfter":
            break
        default:
            break
        }
    }
    
}


extension ShoppingOrderDetailCtr{
    
    
    class StatusCell: JoCellNode {
        let nameL = JoTextNode()
        let infoL = JoTextNode()
        
        let iconV = ASImageNode()
        var status:GoodsOrderStatus = .all
        
        let bt = ASButtonNode()
        
        var verification = GoodsVerification(detail: NSMutableDictionary())
        
        override func mo_model_reload() {
            let order = DataNode.path(node: "__model", mo.model, value: NSMutableDictionary())
            verification = GoodsVerification(detail:order)

//            print("++++Ooooo|\(order["order.status",""])")
            self.status = GoodsOrderStatus(rawValue: order["order.status",""]) ?? .all
            
            let info = status.barInfo(obj: order)
            
            
            
            nameL.attributedText = info.name.ui.font16.cl_fff.astring
            nameL.attributedText = order["order.statusstr",""].loc.ui.font16.cl_fff.astring
            nameL.textNode.maximumNumberOfLines = 2
//            infoL.attributedText = Date()["yyyy-MM-dd HH:mm"].ui.font12.cl_fff.astring
            view.backgroundColor = info.color
            iconV.image = UIImage(named: info.icon)
            
            if info.bt.len > 0
            {
                
                bt.ui.font(size: 12).ncolor(hex: "#fff").padding(insets: [5,7]).ntitle(title: info.bt).set(radius: 2, width: 1, color: .white)
                bt.addTarget(self, action: #selector(doAction(sender:)), forControlEvents: .touchUpInside)
            }
            else{
                bt.alpha = 0
            }
        }
        
        @objc func doAction(sender:ASButtonNode) {
            weak var wself = self
            var model = mo.model
            
            if let __model = DataNode<NSMutableDictionary>.path(node: "__model", mo.model)
            {
                
                model = __model
            }
            
            self.status.doAction(with: sender.actionID, cell: wself, at: mo.controller, order: model)
            
        }
        
        override func specGetter() -> _Spec {
            let spec = _Spec.stack(["h|16",_justfy(.space_between),[36,AppTheme.edge],&-.center], childs: [
                iconV["24",24],
                .stack(["v|8",_grow(1),&-.stretch], childs: [
                    nameL.Spec,
//                    infoL.Spec
                    ])
                ])
            let over = _Spec.over([], over:  .stack([[10,AppTheme.edge],"v",_justfy(.flex_end),&-.stretch], childs: [
                .stack(["h",_justfy(.flex_end)], childs: [
                    bt.Spec
                    ])
                ]), back: spec)
            return over
        }
    }
    
    class GoodsCell: Goods.OrderListCell {
        
        override func addLayoutRules() {
            sellerV = Goods.OrderListCell.SellerNode1()
        }
        override func specGetter() -> _Spec {
            let spec = _Spec.stack(["v",_shrink(1),_justfy(.space_between),&-.stretch], childs: [
                sellerV.Spec,
                goodsV.Spec,
                ])
            return spec
            
        }
    }
    
    class AddressCell: JoCellNode {
        let locV = ASImageNode()
        let nameL = JoTextNode()
        let phoneL = JoTextNode()
        let addressL = JoTextNode()
        
        override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
            locV.image = UIImage(named: "dizhi")?.dynamicImage(color: ._foregroundWeak)
        }
        
        
        override func mo_model_reload() {
            
            view.backgroundColor = ._cellBackground
            separatorHeight = TP.separatorHeight
            separatorColor = UIColor.separator_color
            locV.image = UIImage(named: "dizhi")?.dynamicImage(color: ._foregroundWeak)
            addressL.textNode.maximumNumberOfLines = 2
            let model = DataNode.path(node: "__model", mo.model, value: NSMutableDictionary())
            nameL.attributedText = "\("收货人".loc): \(model["realname",""])".ui.font14.color(color: ._foreground).astring
            phoneL.attributedText = model["mobile",""].ui.font14.color(color: ._foreground).astring
            

//            let list = [model["province",""],model["city",""],model["area",""],model["address",""]]
//
//
//            let newlist = list.filterDuplicate()
//
//            let address = newlist.joined(separator: " ")
            
            let address = GlobalPlaceField.displayStr(address: model)

            addressL.attributedText = address.ui.font12.lineSpace(4).color(color: ._foregroundWeak).astring
            
        }
        
        override func specGetter() -> _Spec {
            let spec:_Spec = _Spec.stack([[16,AppTheme.edge,16,AppTheme.edge],"h|12",_nowrap,&-.flex_start], childs: [
                locV["16",12,[3,0,0,0]],
                .stack(["v|6",_grow(1),_shrink(1),&-.stretch], childs: [
                    .stack(["h|10"], childs: [
                        nameL[_shrink(1)],
                        phoneL[_grow(1)]
                        ]),
                    addressL[_shrink(1)]
                    ]),
                
                ])
            return spec
        }
    }
    
    
    class LogHeader: JoCellNode {
        let logIcon = ASImageNode()
        let logTitleL = JoTextNode()
        let logTitleBk = ASDisplayNode()
        override func addLayoutRules() {
            view.backgroundColor = ._cellBackground
        }
        override func mo_model_reload() {
            logIcon.image = UIImage(named: mo.model["icon",""])?.dynamicImage(color: ___shop.tint)
            logTitleL.attributedText = mo.model["title",""].ui.font14.color(color: ._foregroundWeak).astring
        }
        
        override func specGetter() -> _Spec {
            let title:_Spec = .stack(["h|10",[12,AppTheme.edge,10,-AppTheme.edge],&-.center], childs: [
                logIcon[17,"17"],
                logTitleL[_shrink(1),_grow(1)],
                ])
            return title
        }
    }
    
    class LogCell: JoCellNode {
        
        
        class LogKit: JoTouchNode {
            let indicatorV = ASDisplayNode()
            let textV = JoTextNode()
            var pointColor:UIColor{
                get{
                    if mo.model["__index","xx"] == "0"
                    {
                        return ___shop.tint
                    }
                    return ._foregroundWeak
                }
            }
            
            var contentColor:UIColor{
                get{
                    if mo.model["__index","xx"] == "0"
                    {
                        return ___shop.tint
                    }
                    return ._foregroundWeak
                }
            }
            
            override func mo_model_reload() {
                indicatorV.view.bsui.set(radius: 3, width: nil, color: nil )
                indicatorV.backgroundColor = self.pointColor
                let time = stampToTime(mo.model["time",""])["yyyy-MM-dd HH:mm"]
                textV.attributedText = (time + "    " + mo.model["remark",""]).ui.lineSpace(4).font12.color(color: ._foregroundWeak).astring
                
            }
            
            override func specGetter() -> _Spec {
                return _Spec.stack([[20,AppTheme.edge],"h|8",_nowrap], childs: [
                    indicatorV["6",6,[5,0,0,0]],
                    textV[_shrink(1)],
                    ])
            }
        }
        
        
        
        let listV = JoRuleNode<LogKit>()
        
        override func addLayoutRules() {
            listV.containerConfig = {
                spec in
                spec.direction = ASStackLayoutDirection.vertical
                spec.alignItems = ASStackLayoutAlignItems.stretch
            }
        }
        
        
        override func mo_model_reload() {
            let model = DataNode.path(node: "__model", mo.model, value: NSMutableDictionary())
            listV.nodePath = "order.log"
            listV.mo.model = model
            view.backgroundColor = ._cellBackground
        }
        
        override func specGetter() -> _Spec {
            return .inset([], .zero, child: listV[_shrink(1)])
        }
    }
    
    
    class OrderSnCell: JoCellNode {
        let nameL = JoTextNode()
        let priceL = JoTextNode()
        override func addLayoutRules() {
            view.backgroundColor = ._cellBackground
        }
        
        
        override func mo_model_reload() {
            nameL.attributedText = "[XX]编号".replaceVars(values: OrderScheme.default.name).ui.font13.color(color: ._foregroundWeak).astring
            let no = mo.model.possible("__model.order.ordersn","__model.order.orderno", default:"")
            priceL.attributedText = "\(no)".ui.font13.color(color: ._foregroundWeak).astring
            //            separatorHeight = TP.separatorHeight
            //            separatorColor = UIColor.separator_color
        }
        
        override func specGetter() -> _Spec {
            return _Spec.stack([[16,AppTheme.edge],"h|10",_nowrap,_justfy(.space_between),&-.center], childs: [
                nameL.Spec,
                priceL.Spec
                ])
        }
    }
    
    class PriceCell: JoCellNode {
        
        
        class Kit: JoTouchNode {
            let nameL = JoTextNode()
            let priceL = JoTextNode()
            
            
            
            override func mo_model_reload() {
                nameL.attributedText = mo.model["name",""].ui.font12.cl_888.astring
                let price = mo.model[float:"value",0]
                priceL.attributedText = "¥ \(price.price_display)".ui.font12.cl_888.astring
            }
            
            override func specGetter() -> _Spec {
                return _Spec.stack([[3,AppTheme.edge],"h|10",_nowrap,_justfy(.space_between),&-.center], childs: [
                    nameL.Spec,
                    priceL.Spec
                ])
            }
        }
        
        
        
        let listV = JoRuleNode<Kit>()
        
        override func addLayoutRules() {
            listV.containerConfig = {
                spec in
                spec.direction = ASStackLayoutDirection.vertical
                spec.alignItems = ASStackLayoutAlignItems.stretch
            }
            listV.space = 0
            separatorHeight = TP.separatorHeight
            separatorColor = UIColor._separator
            view.backgroundColor = ._cellBackground
        }
        
        
        
        override func mo_model_reload() {
            let model = DataNode.path(node: "__model", mo.model, value: NSMutableDictionary())
            listV.nodePath = "order.orderprice"
            listV.mo.model = model
        }
        
        override func specGetter() -> _Spec {
            return .inset([], [8,0], child: listV[_shrink(1)])
        }
    }
    
}

